from alibabacloud_cloudauth20190307.client import Client as CloudauthClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_cloudauth20190307 import models as cloudauth_models
from alibabacloud_tea_util.client import Client as UtilClient
from alibabacloud_tea_util import models as util_models
from alibabacloud_credentials.client import Client as CredClient


class Id2MetaVerify:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
            endpoint: str,
    ) -> CloudauthClient:
        # 阿里云账号AccessKey拥有所有API的访问权限，建议您使用RAM用户进行API访问或日常运维。
        # 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里，否则可能导致AccessKey泄露，威胁您账号下所有资源的安全。
        # 本示例通过阿里云Credentials工具从环境变量中读取AccessKey，来实现API访问的身份验证。
        cred = CredClient()
        config = open_api_models.Config(
            credential=cred,
            endpoint=endpoint
        )
        return CloudauthClient(config)

    @staticmethod
    def main(user_name, identify_num) -> None:
        request = cloudauth_models.Id2MetaVerifyRequest(
            param_type='normal',
            user_name=user_name,
            identify_num=identify_num
        )
        response = Id2MetaVerify.id_2_meta_verify_auto_route(request)
        # 不支持服务自动路由。
        # response = Id2MetaVerify.id_2_meta_verify('cloudauth.cn-shanghai.aliyuncs.com', request)
        # print(response.body.request_id)
        # print(response.body.code)
        # print(response.body.message)
        # print(response.body.result_object.biz_code)
        return response

    @staticmethod
    def id_2_meta_verify_auto_route(
            request: cloudauth_models.Id2MetaVerifyRequest,
    ) -> cloudauth_models.Id2MetaVerifyResponse:
        endpoints = [
            'cloudauth.cn-shanghai.aliyuncs.com',
            'cloudauth.cn-beijing.aliyuncs.com'
        ]
        for endpoint in endpoints:
            try:
                response = Id2MetaVerify.id_2_meta_verify(endpoint, request)
                if UtilClient.equal_number(500, response.status_code):
                    continue
                if response is not None and response.body is not None:
                    if UtilClient.equal_string("500", response.body.code):
                        continue
                return response
            except Exception as err:
                print(err)
                continue
        return None

    @staticmethod
    def id_2_meta_verify(
            endpoint: str,
            request: cloudauth_models.Id2MetaVerifyRequest,
    ) -> cloudauth_models.Id2MetaVerifyResponse:
        client = Id2MetaVerify.create_client(endpoint)
        # 创建RuntimeObject实例并设置运行参数。
        runtime = util_models.RuntimeOptions()
        runtime.read_timeout = 5000
        runtime.connect_timeout = 5000
        return client.id_2meta_verify_with_options(request, runtime)

if __name__ == '__main__':
    Id2MetaVerify.main(user_name='张忠俊', identify_num='522229200003256030')
